
import { defineStore } from "pinia";
import { getTypeList, getConfig } from "@/api/index.ts"

type AppStore = {
	consultList ?: any[];
	config ?: any;
	city ?: any;
	cityCode ?: any;
};
const useAppStore = defineStore("app-store", {
	persist: {
		// 仅在客户端使用
	},
	state: () : AppStore => ({
		consultList: [],
		config: {}, // 配置信息，例如主题色等
		city: "武汉", // 城市信息，例如定位城市、当前城市等。
		cityCode: '420100',
	}),

	getters: {

	},

	actions: {
		setCity(cityInfo : Partial<any>) {
			this.$patch({
				cityCode: cityInfo.cityCode
			});
			if (!cityInfo.city) {
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo?location=' + cityInfo.longitude + ',' + cityInfo.latitude + '&key=5ea36757caf400ff5fddc6d05ecbbe6e',
					success: (res) => {
						this.$patch({
							city: res.data?.regeocode?.addressComponent?.city.slice(0, -1) || "徐州",
						});
					},
					fail: (error) => {
						uni.showToast({
							title: "获取位置信息失败",
							icon: "none"
						});
					}
				})
			} else {
				if (cityInfo.city.indexOf('市') != -1) {
					this.$patch({
						city: cityInfo.city.slice(0, -1),
					});
				} else {
					this.$patch({
						city: cityInfo.city,
					});
				}
			}

		},
		getAppConfigValue(key : any) {
			return this.config[key]
		}, // 这里应该调用接口获取配置信息，并更新state中的config字段。
		getAppConfig() {
			getConfig().then((res : any) => {
				this.$patch({
					config: res
				});
			});
		},
		getConsult(id : number) : any {
			return this.consultList.find((item : any) => item.id === id)
		},
		getConsultList() {
			getTypeList().then((res : any[]) => {
				this.$patch({
					consultList: res,
				})
			});
		}
	},
})

export default useAppStore;